class Solution(object):
    def findCircleNum(self, isConnected):
        """
        :type isConnected: List[List[int]]
        :rtype: int
        """
        n = len(isConnected)
        p = [i for i in range(n)]
        rank = [1] * n
        self.part = n

        def find(x):
            if p[x] == x:
                return x
            else:
                p[x] = find(p[x])
                return p[x]

        def union(x, y):
            rootx = find(x)
            rooty = find(y)
            if rootx != rooty:
                self.part -= 1
                if rank[rootx] < rank[rooty]:
                    p[rootx] = rooty
                else:
                    p[rooty] = rootx
                    if rank[rootx] == rank[rooty]:
                        rank[rootx] += 1

        for i in range(n):
            for j in range(i + 1, n):
                if isConnected[i][j] == 1:
                    union(i, j)

        return self.part

data = Solution()
isConnected = [[1, 1, 0], [1, 1, 0], [0, 0, 1]]
print(data.findCircleNum(isConnected))
